package migrations

import (
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func AutoMigrate() {

	// 配置MySQL数据库连接信息
	dsn := "root:root@tcp(127.0.0.1:3306)/zero?charset=utf8mb4&parseTime=True&loc=Local"

	// 连接MySQL数据库
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
		// 为了确保数据一致性，GORM 会在事务里执行写入操作（创建、更新、删除）。如果没有这方面的要求，您可以在初始化时禁用它，这样可以获得60%的性能提升
		SkipDefaultTransaction: true,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "zero_", // 表名前缀
			SingularTable: false,   // 单数表名
			NoLowerCase:   false,   // 关闭小写转换
		},
	})
	if err != nil {
		log.Fatalf("Failed to connect database: %v", err)
	}

	// 自动创建和更新表结构
	err = db.Set("gorm:table_options", "ENGINE=InnoDB").Set("gorm:table_options", "COMMENT='用户信息表'").AutoMigrate(&AdminAdmin{})

	if err != nil {
		log.Fatalf("Failed to auto migrate database: %v", err)
	}
	err = db.Set("gorm:table_options", "ENGINE=InnoDB").Set("gorm:table_options", "COMMENT='角色表'").AutoMigrate(&AdminGroup{})

	if err != nil {
		log.Fatalf("Failed to auto migrate database: %v", err)
	}

	err = db.Set("gorm:table_options", "ENGINE=InnoDB").Set("gorm:table_options", "COMMENT='菜单表'").AutoMigrate(&AdminRule{})

	if err != nil {
		log.Fatalf("Failed to auto migrate database: %v", err)
	}

	// 关闭数据库连接
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("Failed to get database connection: %v", err)
	}
	defer sqlDB.Close()
}
